package com.iot08.api.service;

import com.iot08.api.constant.Constant;
import com.iot08.common.entity.app.Account;
import com.iot08.common.entity.app.Adversters;
import com.iot08.common.entity.app.AdverstersComInfo;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.PackageTools;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2021/1/5 16:40
 */
@Slf4j
@Service
public class AdverstersService extends BaseService<Adversters> {

    @Resource
    private AccountService accountService;

    //免广告
    @Value("${ad.app.audit.account:2c312c229d5d523aad6a68ef}")
    private String AD_APP_AUDIT_ACCOUNT;

    /**
     * 广告配置获取
     *
     * @param openid
     * @param userAgent
     * @param version
     * @time: 2021/1/14 14:49
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getInfo(String openid, String userAgent, String version) {
        //请求头数据解析处理
        if (StringUtil.isNotBlank(userAgent)) {
            if (userAgent.contains("Android")) {
                //android User-Agent: swatch/1.6.0(SM-N9500;Android;9)
                String[] sysInfoList = userAgent.split(";");
                String[] tempArr = sysInfoList[0].split("\\(");
                for (String value : sysInfoList) {
                    tempArr = tempArr[0].split("/");
                    version = tempArr[tempArr.length - 1];
                }
            }
        }

        Account account = accountService.findById(openid);
        if (account == null) {
            log.error("Account is null. id={}. getInfo", openid);
            return ResponseMap.fail(ResponseEnum.STATUS2000.getCode(), ResponseEnum.STATUS2000.getMsg());
        }
        ResponseMap res = ResponseMap.success();
        res.put("openid", openid);
        res.put("accesstoken", accountService.getAccesstoken(account));
        //默认关闭开屏
        res.put("isOpen", 0);

        //如果是iOS的e路相伴的: 需要补充一下 ADHUB <=> ADSCOPE
        //判断是否是马甲包 (e路相伴)
        boolean isTCSH = false;
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //获取不区分大小写, 统一小写
        userAgent = req.getHeader("user-agent");
        String bundleid = req.getHeader("Bundleid"); //iOS 才有
        if(StringUtil.isBlank(bundleid)){
            bundleid = req.getHeader("packagename"); //安卓有
        }
        int requestTypeWithUserAgent = PackageTools.getRequestTypeWithUserAgent(userAgent, bundleid);
        if (requestTypeWithUserAgent == 101 || requestTypeWithUserAgent == 201) {
            //其他马甲包
            if(bundleid != null && bundleid.equalsIgnoreCase("com.jh.watch")){
                isTCSH = true;
            }

        }
//        if(requestTypeWithUserAgent == 201 && isTCSH == true){
//            //临时, 安卓-e路相伴 不打开广告
//            return res;
//        }


        List<Map<String, Object>> adList = new ArrayList<>();
        Query query = new Query(Criteria.where("status").is("1")).with(Sort.by(Sort.Order.asc("index")));
        List<Adversters> adverstersList = this.find(query);
        if (adverstersList != null) {
            res.put("isOpen", 1);
            int num = 1;
            for (Adversters ad : adverstersList) {
                Map<String, Object> temp = new HashMap<>();
                if (StringUtil.isNotBlank(ad.getStartTime1()) && StringUtil.isNotBlank(ad.getEndTime1())) {
                    temp.put("adverster_id", num);
                    temp.put("adverster_name", ad.getShortName());
                    temp.put("ad_start", ad.getStartTime1());
                    temp.put("ad_finish", ad.getEndTime1());
                    adList.add(temp);
                    num++;
                }
                if (StringUtil.isNotBlank(ad.getStartTime2()) && StringUtil.isNotBlank(ad.getEndTime2())) {

                    temp.put("adverster_id", num);
                    temp.put("adverster_name", ad.getShortName());
                    temp.put("ad_start", ad.getStartTime2());
                    temp.put("ad_finish", ad.getEndTime2());
                    adList.add(temp);
                    num++;
                }
                if (StringUtil.isNotBlank(ad.getStartTime3()) && StringUtil.isNotBlank(ad.getEndTime3())) {

                    temp.put("adverster_id", num);
                    temp.put("adverster_name", ad.getShortName());
                    temp.put("ad_start", ad.getStartTime3());
                    temp.put("ad_finish", ad.getEndTime3());
                    adList.add(temp);
                    num++;
                }
                if(isTCSH){
                    //如果是e路相伴,再加一个 ADHUB 的兼容一下
                    if("ADSCOPE".equalsIgnoreCase(ad.getShortName())){
                        temp.put("adverster_id", num);
                        temp.put("adverster_name", "ADHUB");
                        adList.add(temp);
                        num++;
                    }

                }

            }
            if(isTCSH && requestTypeWithUserAgent == 201 && account.getVersion().equalsIgnoreCase("1.4.2")){
                //如果是安卓(201)的e路相伴 1.4.2 的版本只保留 YQ一个广告
                Map<String, Object> onlyYQ = new HashMap<>();
                onlyYQ.put("adverster_id", 1);
                onlyYQ.put("adverster_name", "YQ");
                onlyYQ.put("ad_start", "00:00");
                onlyYQ.put("ad_finish", "23:59");
                adList.clear();
                adList.add(onlyYQ);
            }
        }

        //判断是否是审核账号
        if (AD_APP_AUDIT_ACCOUNT.equals(openid)) {
            //关闭开屏
            res.put("isOpen", 0);
        }



        res.put("adList", adList);
        res.put("openid", openid);
        res.put("accesstoken", account.getAccesstoken());


//        if (info == null) {
//            //默认配置
//            Map<String, Object> adFillDic = new HashMap<>();
//            Map<String, Object> temp = new HashMap<>();
//            temp.put("adverster_name", "YQ");
//            adFillDic.put("first", temp);
//            temp = new HashMap<>();
//            temp.put("adverster_name", "BIRD");
//            adFillDic.put("second", temp);
//
//            res.put("adFillDic", adFillDic);
//            res.put("adFailUserADName", "YQ");
//            //广告的启用方式 (用上面的方式名 adList(时间), adListWeight(权重), adFillDic(补量))
//            res.put("adStartFun", "adListWeight");
//            //审核免除广告的 账号openid
//            res.put("appAuditAccount", Constant.APP_AUDIT_ACCOUNT);
//            //内部广告开关
//            res.put("appInternalADswitch", true);
//        } else {
//            res.put("appAuditAccount", info.getAppAuditAccount());
//            res.put("adStartFun", info.getAdStartFun());
//            res.put("adFailUserADName", info.getAdFailUserADName());
//            res.put("adFillDic", info.getAdFillDic());
//            if (StringUtil.isNotBlank(info.getApiWordLink())) {
//                res.put("adPasswordURL", info.getApiWordLink().replace(" ", ""));
//            }
//            if ("1".equals(info.getAppInternalADswitch())) {
//                res.put("appInternalADswitch", true);
//            } else {
//                res.put("appInternalADswitch", false);
//            }
//        }
//        if (info != null && StringUtil.isNotBlank(info.getInternalADFreeVersion()) && StringUtil.isNotBlank(version)) {
//            String fversion = info.getInternalADFreeVersion().replace(".", "");
//            version = version.replace(".", "");
//            if (fversion.length() > version.length()) {
//                for (int i = 0; i < fversion.length() - version.length(); i++) {
//                    version += "0";
//                }
//            } else if (fversion.length() < version.length()) {
//                for (int i = 0; i < version.length() - fversion.length(); i++) {
//                    fversion += "0";
//                }
//            }
//            if (version.equals(fversion)) {
//                res.put("appInternalADswitch", false);
//            }
//        }
        log.info("用户:{} 获取开屏广告配置接口成功 res:{}",openid, res);
        return res;
    }
}
